package com.msunsoft.dataset.dictionary.ecache;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * Ehcache 工具类
 * @author xucl
 *
 */
public class EhcacheUtils {
	private static String EHCACHE_CONFIG="com/msunsoft/dataset/dictionary/ecache/ehcache-local.xml";
	private static CacheManager cacheManager = null;
	private static String cacheName = "dictionaryCache";
	static{
		
		String path = EhcacheUtils.class.getClassLoader().getResource(EHCACHE_CONFIG).getPath();
		cacheManager = CacheManager.create(path);
	}
	
	/**
	 * 获取dictionaryCache缓存
	 */
	public static Object get(String key){
		return get(cacheName,key);
	}
	
	/**
	 * 获取缓存
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static Object get(String cacheName, String key) {
		Element element = getCache(cacheName).get(key);
		return element==null?null:element.getObjectValue();
	}
	
	/**
	 * 获得一个Cache，没有则创建一个。
	 * @param cacheName
	 * @return
	 */
	private static Cache getCache(String cacheName){
		Cache cache = cacheManager.getCache(cacheName);
		return cache;
	}
	
	/**
	 * 写入dictionaryCache缓存
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put( String key, Object value) {
		put(cacheName, key, value);
	}
	
	/**
	 * 写入缓存
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put(String cacheName, String key, Object value) {
		Element element = new Element(key, value);
		getCache(cacheName).put(element);
	}

	/**
	 * 从SYS_CACHE缓存中移除
	 * @param key
	 * @return
	 */
	public static void remove(String key) {
		remove(cacheName, key);
	}
	
	/**
	 * 从缓存中移除
	 * @param cacheName
	 * @param key
	 */
	public static void remove(String cacheName, String key) {
		getCache(cacheName).remove(key);
	}
}
